package com.fangfei.runtest.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fangfei.runtest.Config.TestConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class TestModel {
    private static final Logger logger = LoggerFactory.getLogger(TestModel.class);

    private TestConfig testConfig;

    public TestModel(TestConfig testConfig){
        this.testConfig = testConfig;
    }

    public void start(){
        //where id=9
        List rows = testConfig.getJdbcTemplate().queryForList(testConfig.getSelectsql());
        Iterator it = rows.iterator();
        while(it.hasNext()) {
            Map urlMap = (Map)it.next();
            channel((String) urlMap.get("url"), (String) urlMap.get("args"), (String) urlMap.get("data"));
        }
    }

    public void channel(String url, String args,String data){
        //start
        //logger.info(url);

        //this map initialize
        String[] argsarr = args.split(",");
        for(String r : argsarr){
            String[] arr = r.split(":");
            if (0 == arr[1].indexOf("get")){
                Method method = null;
                try {
                    Class<?> classFunction = TestFunctionModel.class;
                    method = classFunction.getMethod(arr[1]);
                    Object methodData = method.invoke(classFunction.newInstance());
                    testConfig.getUserMap().put(arr[0], methodData);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            }else if("map".equals(arr[1])){
                //tmMap.put(arr[0], tmMap.get(arr[0]));
            }else{
                testConfig.getUserMap().put(arr[0], arr[1]);
            }
        }

        //build2action
        String returnStr = buildPostJson(url, argsarr);

        //data
        if (!data.isEmpty()){
            String[] argsarrs = data.split(",");
            for(String r : argsarrs){
                String[] arr = r.split(":");
                if (0 == arr[1].indexOf("set")) {
                    Method method = null;
                    try {
                        Class<?> classFunction = TestFunctionModel.class;
                        method = classFunction.getMethod(arr[1], String.class, TestConfig.class);
                        Object returnDate = method.invoke(classFunction.newInstance(), returnStr, testConfig);
                        testConfig.getUserMap().put(arr[0], returnDate);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    }
                }else if("map" == arr[1]){
                    //tmMap.put(arr[0], tmMap.get(arr[0]));
                }else{
                    testConfig.getUserMap().put(arr[0], arr[1]);
                }
            }
        }

        //end
        //logger.info(tmMap.toString());

    }

    //build2action json格式传输
    public String buildPostJson(String url, String[] argsarr){
        //model3
        JSONObject postData = new JSONObject();
        for(String r : argsarr){
            String[] arr = r.split(":");
            postData.put(arr[0], testConfig.getUserMap().get(arr[0]));
        }
        postData.put("random",System.currentTimeMillis()); //随机参数
        logger.info(url+postData.toString());

        //action
        JSONObject json = testConfig.getRestTemplate().postForEntity(testConfig.getBaseUrl()+url, postData, JSONObject.class).getBody();
        String rstr = JSON.toJSONString(json);
        logger.info(url+rstr);

        return rstr;
    }

    //build2action String格式传输
    public String buildPostString(String url, String[] argsarr){
        //model1
        MultiValueMap<String, Object> postData= new LinkedMultiValueMap<String, Object>();
        for(String r : argsarr){
            String[] arr = r.split(":");
            postData.add(arr[0], testConfig.getUserMap().get(arr[0]));
        }
        //bmap.add("random", getnickname());
        logger.info(url+postData.toString());

        //action
        String rstr = testConfig.getRestTemplate().postForObject(testConfig.getBaseUrl()+url, postData, String.class);
        logger.info(url+rstr);

        return rstr;
    }

    //build2action HttpEntity格式传输
    public String buildPostEntity(String url, String[] argsarr){
        //model2
        MultiValueMap<String, Object> postData= new LinkedMultiValueMap<String, Object>();
        for(String r : argsarr){
            String[] arr = r.split(":");
            postData.add(arr[0], testConfig.getUserMap().get(arr[0]));
        }
        //bmap.add("random", getnickname());
        logger.info(url+postData.toString());

        //action
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postData);
        ResponseEntity<String> responseEntity = testConfig.getRestTemplate().postForEntity(testConfig.getBaseUrl()+url, httpEntity, String.class);
        String rstr =responseEntity.getBody();
        logger.info(url+rstr);

        return rstr;
    }







}
